import { exportExcelApi, getCheckLog, getProgramOptions } from '@/services/api';
import { removeEmptyValues } from '@/utils';
import { FileSearchOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Button, Tag, message } from 'antd';
import { useRef } from 'react';

const Binding: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const formRef = useRef<any>();

  // 查询所有商户
  const { data: merchantList } = useRequest(async () => {
    return await getProgramOptions();
  });

  const columns: any = [
    {
      title: '商户',
      dataIndex: 'user__name',
      valueType: 'select',
      render: (text: string, record: any) => {
        return (
          <div>
            {record?.user?.id} - {record?.user?.name}
          </div>
        );
      },
      fieldProps: {
        onChange: (value) => {
          formRef?.current?.submit();
        },
        options:
          merchantList?.data?.map((e) => {
            return {
              label: e?.label,
              value: e?.label,
            };
          }) ?? [],
        showSearch: true,
      },
    },
    {
      title: '时间',
      dataIndex: 'create_time__range',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            create_time__range: [
              `${value?.[0]} 00:00:00`,
              `${value[1]} 23:59:59`,
            ],
          };
        },
      },
      fieldProps: {
        onChange: (value) => {
          formRef?.current?.submit();
        },
      },
    },
    {
      title: '时间',
      dataIndex: 'create_time',
      hideInSearch: true,
    },
    {
      title: '校验号码',
      dataIndex: 'mobile',
    },
    {
      title: '校验结果',
      dataIndex: 'status_text',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Tag
            color={record?.status === 1 ? 'success' : 'error'}
            bordered={false}
          >
            {record?.status_text}
          </Tag>
        );
      },
    },
    {
      disable: true,
      title: '校验结果',
      dataIndex: 'status',
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        1: {
          text: '成功',
        },
        2: {
          text: '失败',
        },
      },
      fieldProps: {
        onSelect: (value) => {
          formRef?.current?.submit();
        },
      },
    },
  ];

  const { loading, runAsync } = useRequest(
    async (_parames) => {
      return await exportExcelApi({
        ..._parames,
      });
    },
    {
      manual: true,
    },
  );

  return (
    <>
      <ProTable
        bordered
        columns={columns}
        actionRef={actionRef}
        formRef={formRef}
        cardBordered
        request={async (_parame) => {
          const { pageSize, current, ...ret } = _parame;
          const { data } = await getCheckLog({
            page: current,
            size: pageSize,
            filters: JSON.stringify({
              ...removeEmptyValues({ ...ret }),
            }),
          });
          return {
            data: data?.list ?? [],
            success: true,
            total: data?.count,
          };
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<FileSearchOutlined />}
            onClick={async () => {
              let _faileName: string = '校验日志';
              let _header: any = ['商户', '时间', '绑定号码', '校验结果'];
            // 获取表格的搜索框信息
              const _search = formRef?.current?.getFieldsValue();
              console.log('_search',_search);
              
              try {
                await runAsync({
                  filename: _faileName,
                  header: _header,
                  fields: ['mp_users.user_id.name', 'create_time', 'mobile', 'status'],
                  table: 'journal_checklog',
                });

                message.success(`文件${_faileName}导出成功`);
              } catch (error) {}
            }}
            type="primary"
            loading={loading}
          >
            导出
          </Button>,
        ]}
      />
    </>
  );
};

export default Binding;
